//
//  GDScanViewController.m
//  GDPay
//
//  Created by apple on 16/2/3.
//  Copyright (c) 2016年 HuaZhengInfo. All rights reserved.
//

#import "GDScanViewController.h"
#import <AVFoundation/AVFoundation.h>

#define kBorderW 60
#define kMargin 15



@interface GDScanViewController ()<AVCaptureMetadataOutputObjectsDelegate,UIAlertViewDelegate>

@property (nonatomic, strong) AVCaptureSession * session;
@property (nonatomic, weak) UIView * maskView;


@end

@implementation GDScanViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    self.tabBarController.tabBar.hidden = YES;
    UITapGestureRecognizer * gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(diaMiss)];
    [self.view addGestureRecognizer:gesture];
    self.view.clipsToBounds = YES;
    
    [self setupMaskView];
//    [self setupBottomBar];
    [self setupScanWindowView];
    [self beginScanning];
}

- (void)setupMaskView{

    UIView * mask = [[UIView alloc] init];
    _maskView = mask;
    mask.layer.borderColor = GARY.CGColor;
    mask.layer.borderWidth = kBorderW;
    mask.bounds = CGRectMake(0, 0, self.view.frame.size.width + kBorderW + kMargin * 2, self.view.frame.size.height);
    mask.center = self.view.center;
//    CGRect temp = self.view.frame;
//    temp.origin.y = 0;
//    self.view.frame = temp;


    [self.view addSubview:mask];
    
    
}

- (void)setupBottomBar{

    UIView * bottomBar =[[UIView alloc] initWithFrame:CGRectMake(0, SCR_H * 0.9, SCR_W, SCR_H * 0.1)];
    bottomBar.backgroundColor = RGBA(0, 0, 0, 0.8);
    [self.view addSubview:bottomBar];
    
}

- (void)setupScanWindowView{

    CGFloat scanWindowH = SCR_H * 0.9 - kBorderW * 2;
    CGFloat scanWindowW = SCR_W - kMargin * 2;
    UIView * scanWindow = [[UIView alloc] initWithFrame:CGRectMake(kMargin, kBorderW + 33, scanWindowW, scanWindowH)];
    scanWindow.clipsToBounds = YES;
    [self.view addSubview:scanWindow];
    
    CGFloat scanNetImageViewH = SCR_H * 0.5;
    CGFloat scanNetImageViewW = scanWindow.frame.size.width;
    UIImageView * scanNetImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"scan_net"]];

    scanNetImageView.frame = CGRectMake(0, -scanNetImageViewH, scanNetImageViewW, scanNetImageViewH);
    CABasicAnimation * animation = [CABasicAnimation animation];
    animation.keyPath = @"transform.translation.y";
    animation.byValue = @(scanWindowH);
    animation.duration = 1.0;
    animation.repeatCount = MAXFLOAT;
    [scanNetImageView.layer addAnimation:animation forKey:nil];
    [scanWindow addSubview:scanNetImageView];
    
    CGFloat buttonWH = 18;
    
    // 上左边按钮
    UIButton * topLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, buttonWH, buttonWH)];
    [topLeft setImage:[UIImage imageNamed:@"scan_1"] forState:UIControlStateNormal];
    [scanWindow addSubview:topLeft];
    
    // 上右边按钮
    UIButton * topRight = [[UIButton alloc] initWithFrame:CGRectMake(scanWindowW - buttonWH, 0, buttonWH, buttonWH)];
    [topRight setImage:[UIImage imageNamed:@"scan_2"] forState:UIControlStateNormal];
    [scanWindow addSubview:topRight];
    
    // 底部左按钮
    UIButton * buttomLeft = [[UIButton alloc] initWithFrame:CGRectMake(0, scanWindowH - buttonWH, buttonWH, buttonWH)];
    [buttomLeft setImage:[UIImage imageNamed:@"scan_3"] forState:UIControlStateNormal];
    [scanWindow addSubview:buttomLeft];
    
    
    // 底部右按钮
    UIButton * buttomRight = [[UIButton alloc] initWithFrame:CGRectMake(topRight.frame.origin.x, buttomLeft.frame.origin.y, buttonWH, buttonWH)];
    [buttomRight setImage:[UIImage imageNamed:@"scan_4"] forState:UIControlStateNormal];
    
    [scanWindow addSubview:buttomRight];

    
    
}

- (void)beginScanning{

    // 获取摄像设备
    AVCaptureDevice * device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
    
    // 创建输入流
    AVCaptureDeviceInput * input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    
    if (!input) {
        return;
    }
    
    // 创建输出流
    AVCaptureMetadataOutput * output = [[AVCaptureMetadataOutput alloc] init];
    output.rectOfInterest =  CGRectMake(0.1, 0, 0.9, 1.0);
    
    // 设置代理 在主线程刷新
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    // 初始化链接对象
    _session = [[AVCaptureSession alloc] init];
    
    // 高质量采集
    [_session setSessionPreset:AVCaptureSessionPresetHigh];
    
    [_session addInput:input];
    [_session addOutput:output];
    
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    AVCaptureVideoPreviewLayer * layer = [AVCaptureVideoPreviewLayer layerWithSession:_session];
    layer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    
    layer.frame = self.view.layer.bounds;
    [self.view.layer insertSublayer:layer atIndex:0];
    
    // 开始捕获
    [_session startRunning];
    
    
    
    
    
}

- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection{

    if (metadataObjects.count >  0) {
        [_session stopRunning];
        AVMetadataMachineReadableCodeObject * object = [metadataObjects objectAtIndex:0];
        UIAlertView * alterView = [[UIAlertView alloc] initWithTitle:@"扫描结果" message:object.stringValue delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"再次扫描", nil];
        [alterView show];
    }
}

- (void)diaMiss{

    [self.navigationController popViewControllerAnimated:YES];
    
    
}

- (void)willMoveToParentViewController:(UIViewController *)parent{

    if (!parent) {
        self.navigationController.navigationBar.hidden = NO;
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (buttonIndex == 0) {
        [self diaMiss];
    }else if (buttonIndex == 1){
    
        [_session startRunning];
        
    }
}


@end
